package CategoryService

import (
	"gdshop-admin-go-api/app/request/CategoryReq"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func Order(r *ghttp.Request, parames *CategoryReq.Order) *response.JsonResponse {
	tx, err := g.DB().Ctx(r.GetCtx()).Begin()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 方法退出时检验返回值，
	// 如果结果成功则执行tx.Commit()提交,
	// 否则执行tx.Rollback()回滚操作。
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	for _, item := range parames.Data {
		// 排除 ID = 0 的
		if item.Id < 1 {
			continue
		}
		_, err = tx.Table("category").Unscoped().Where("id",
			item.Id,
		).Update(g.Map{
			"parent_id": item.ParentId,
			"sort":      item.Sort,
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	return response.SuccessByRequestMessage(nil, "排序成功")
}
